package com.handpay.framework.swiper;

import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.text.TextUtils;

import com.handpay.framework.ClientEngine;
import com.handpay.zztong.hp.R;
import com.handpay.zztong.hp.config.ZZTConfig;
import com.handpay.zztong.hp.log.HPLog;
import com.handpay.zztong.hp.login.activity.WelcomeActivity;
import com.handpay.zztong.hp.swiper.SwiperUtils;

/**
 * Created by jmshuai on 2014/4/28.
 */
public class SwiperDetectService extends Service {
    private final static String TAG = "SwiperDetectService";
    public final static String SWIPER_CONNECT_STATE_ACTION = "swiper_connect_state";
    public final static String SWIPER_CONNECT_STATE_KEY = "swiper_connect_state";
    public final static String SWIPER_TYPE_KEY = "swiper_type";
    /**
     * 如果该消息被处理过，将这个key对应的value设置为true
     */
    public final static String SWIPER_RESULT_KEY = "swiper_result";
    BroadcastReceiver mBroadcastReceiver;

    @Override
    public void onCreate() {
        super.onCreate();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Intent.ACTION_HEADSET_PLUG);
        intentFilter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
        intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
        intentFilter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
        intentFilter.addCategory(Intent.CATEGORY_DEFAULT);
        mBroadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                sendOutBroadcast(intent);
            }
        };
        registerReceiver(mBroadcastReceiver, intentFilter);
    }

    public void sendOutBroadcast(final Intent intent) {
//        String action = intent.getAction();
        boolean state = false;
        IPersonalSwiper.SwiperType swiperType = null;
        if (Intent.ACTION_HEADSET_PLUG.equals(intent.getAction())) {
            HPLog.i(TAG, "耳机状态：ACTION_HEADSET_PLUG");
            boolean hasHeadset = (intent.getIntExtra("state", 0) == 1);
            boolean hasMicroPhone = (intent.getIntExtra("microphone", 0) == 1);
            if (hasHeadset && hasMicroPhone) {
                state = true;
                HPLog.i(TAG, "耳机插入");
                ClientEngine.getInstance().saveGlobal(ClientEngine.VOICE_PLUGIN, true);
            } else {
                state = false;
                HPLog.i(TAG, "耳机拔出");
                ClientEngine.getInstance().saveGlobal(ClientEngine.VOICE_PLUGIN, false);
            }
            swiperType = IPersonalSwiper.SwiperType.VOICE;
        } else if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(intent.getAction())) {
            HPLog.i(TAG, "蓝牙状态：ACTION_ACL_CONNECTED");
            state = true;
            swiperType = IPersonalSwiper.SwiperType.BLUETOOTH;
        } else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(intent.getAction())) {
            HPLog.i(TAG, "蓝牙状态：ACTION_ACL_DISCONNECTED");
            // 获取断开连接的蓝牙设备add？会不会存在两个蓝牙设备add一致？使用uuid？
            BluetoothDevice bd = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            String connectedBTAdd = SwiperUtils.getConnectedBTMac();
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ECLAIR)
                HPLog.i(TAG, "connectedAdd:" + connectedBTAdd + " disAdd:" + (bd == null ? "null" : bd.getAddress()));
            // 只有当断开的蓝牙设备的mac是当前连接的蓝牙设备的时候，才发送给程序，刷卡器断开连接了
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ECLAIR) {
                if (null != bd && !TextUtils.isEmpty(connectedBTAdd) && connectedBTAdd.equals(bd.getAddress())) {
                    SwiperUtils.saveConnectedBTMac(null);
                    state = false;
                }
            }
            swiperType = IPersonalSwiper.SwiperType.BLUETOOTH;
        } else if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(intent.getAction())) {
            final int bluetoothState = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
            swiperType = IPersonalSwiper.SwiperType.BLUETOOTH;
            HPLog.i(TAG, "蓝牙状态：ACTION_STATE_CHANGED");
            switch (bluetoothState) {
                case BluetoothAdapter.STATE_OFF: {
                    SwiperUtils.saveConnectedBTMac(null);
                    state = false;
                    HPLog.i(TAG, "STATE_OFF");
                    break;
                }
                case BluetoothAdapter.STATE_TURNING_ON: {
                    HPLog.i(TAG, "TURNING_ON");
                    break;
                }
                case BluetoothAdapter.STATE_ON: {
                    HPLog.i(TAG, "STATE_ON");
                    break;
                }
            }
        }
//        // 只发送断开的消息，连接上的消息不处理！因为改为手动的使用哪种刷卡器
        if (!state) {
            Intent sendOutIntent = new Intent(SWIPER_CONNECT_STATE_ACTION);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.DONUT) {
                sendOutIntent.setPackage(getPackageName());
            }
            sendOutIntent.putExtra(SWIPER_CONNECT_STATE_KEY, state);
            sendOutIntent.putExtra(SWIPER_TYPE_KEY, swiperType.ordinal());
            HPLog.i(TAG, sendOutIntent.toString());
            sendOrderedBroadcast(sendOutIntent,null);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        HPLog.e(TAG, "onDestroy");
        decreasePriority();
        this.unregisterReceiver(mBroadcastReceiver);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
//        promotePriority();
        return START_NOT_STICKY;
    }

    private static final int NOTIFICATION_ID = 1314;

    // 通过startForeground来提高优先级
    private void promotePriority() {
        Notification.Builder builder = new Notification.Builder(this);
//        builder.setContentInfo("补充内容");
//        builder.setContentText("主内容区");
        builder.setContentTitle(getString(R.string.app_name));
        builder.setSmallIcon(R.drawable.ic_launcher);
//        builder.setTicker("新消息");
        Intent intent = new Intent(this, WelcomeActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
        builder.setContentIntent(pendingIntent);
        Notification notification = null;
            notification = builder.build();

        this.startForeground(NOTIFICATION_ID, notification);
    }

    private void decreasePriority() {
        HPLog.i(TAG, "decreasePriority");
        this.stopForeground(true);
    }

    public IBinder onBind(Intent intent) {
        return null;
    }
}
